package com.natsuki.lock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

public class RedisLockUtils {

    @Autowired
    RedisTemplate redisTemplate;

    //锁的过期时间
    protected long internalLockLeaseTime = 30000;

    //获取锁的超时时间
    private long timeOut=30000;

    @Value("${lex.str}")
    String str="";

    //加锁的方法
    public boolean tryLock(String lockKey,String requestId){

        System.out.println(str);
        //获取到当前的时间
        long start = System.currentTimeMillis();

        //获取到当前的线程名称
        String name = Thread.currentThread().getName();

        for (;;){
            Boolean lock= (Boolean) redisTemplate.execute((RedisCallback) connection->{
                Boolean flag = connection.setNX(lockKey.getBytes(), requestId.getBytes());
                return flag;
            });
            if (lock){
                System.out.println("线程 "+name +" 加锁成功" );
                return true;
            }
            //判断
            long time = System.currentTimeMillis() - start;
            if (time>=timeOut){
                System.out.println("线程 "+name +" 获取锁超时" );
                return false;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //释放锁的方法
}
